<template>
    <div class="user-manage">
        <!-- 面包屑和标题 -->
        <el-breadcrumb separator="/" class="mb-2">
            <el-breadcrumb-item>系统管理</el-breadcrumb-item>
            <el-breadcrumb-item>用户管理</el-breadcrumb-item>
        </el-breadcrumb>
        <div class="page-title">用户管理</div>

        <!-- 查询区 -->
        <el-form :inline="true" :model="query" class="query-form">
            <el-form-item>
                <el-input v-model="query.UserName" placeholder="用户账号/ID/手机号" clearable style="width: 220px;" />
            </el-form-item>
            <el-form-item>
                <el-select v-model="query.MembershipLevel" placeholder="会员等级" clearable style="width: 150px;">
                    <el-option label="黄金会员" value="黄金会员" />
                    <el-option label="白银会员" value="白银会员" />
                    <el-option label="铜牌会员" value="铜牌会员" />
                </el-select>
            </el-form-item>
            <el-form-item>
                <el-select v-model="query.UserTags" placeholder="用户标签" clearable style="width: 150px;">
                    <el-option label="标签A" value="A" />
                    <el-option label="标签B" value="B" />
                    <el-option label="标签C" value="C" />
                </el-select>
            </el-form-item>
            <el-form-item>
                <el-select v-model="query.RegistrationChannel" placeholder="注册渠道" clearable style="width: 150px;">
                    <el-option label="渠道1" value="1" />
                    <el-option label="渠道2" value="2" />
                </el-select>
            </el-form-item>
            <el-form-item>
                <el-date-picker v-model="registerTime" type="daterange" placeholder="注册时间" range-separator="至"
                    start-placeholder="开始日期" end-placeholder="结束日期" style="width: 230px;" />
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="onSearch">查询</el-button>
                <el-button @click="onReset">重置</el-button>
                <el-button type="text" @click="showAdvanced = true">高级筛选</el-button>
            </el-form-item>
        </el-form>

        <!-- 高级筛选弹窗 -->
        <el-dialog v-model="showAdvanced" title="" width="800px" :modal="false" class="dialog-right"
            @close="resetAdvancedForm">
            <b style="font-size: 30px; font-weight: bold;">高级筛选</b>
            <el-form :model="advanced" label-width="100px" style="margin-top: 60px;">
                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item label="用户账号">
                            <el-input v-model="advanced.UserName" placeholder="用户账号/ID/手机号" clearable />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="会员等级">
                            <el-select v-model="advanced.MembershipLevel" placeholder="选择会员等级" clearable
                                style="width: 100%;">
                                <el-option label="黄金会员" value="黄金会员" />
                                <el-option label="白银会员" value="白银会员" />
                                <el-option label="铜牌会员" value="铜牌会员" />
                                <!-- 根据需要添加更多等级 -->
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item label="用户标签">
                            <el-select v-model="advanced.UserTags" placeholder="选择用户标签" clearable style="width: 100%;">
                                <el-option label="开发" value="开发" />
                                <el-option label="用户注册" value="用户注册" />
                                <!-- 根据需要添加更多标签 -->
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="注册渠道">
                            <el-select v-model="advanced.RegistrationChannel" placeholder="选择注册渠道" clearable
                                style="width: 100%;">
                                <el-option label="开发内部" value="开发内部" />
                                <el-option label="app注册" value="app注册" />
                                <!-- 根据需要添加更多渠道 -->
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item label="注册时间">
                            <el-date-picker v-model="advancedRegisterTime" type="daterange" range-separator="至"
                                start-placeholder="开始日期" end-placeholder="结束日期" style="width: 100%;"
                                value-format="YYYY-MM-DD" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="账号状态">
                            <el-radio-group v-model="advanced.IsEnabled">
                                <el-radio :value="true">正常</el-radio>
                                <el-radio :value="false">禁用</el-radio>
                            </el-radio-group>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item label="消费金额">
                            <el-select v-model="advanced.consumptionAmountRange" placeholder="选择消费金额范围" clearable
                                style="width: 100%;">
                                <el-option v-for="option in consumptionAmountOptions" :key="option.value"
                                    :label="option.label" :value="option.value" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            <div style=" margin-top: 20px; margin-left: 40px;">
                <el-button @click="showAdvanced = false">取消</el-button>
                <el-button type="primary" @click="onAdvancedConfirm">确定</el-button>
            </div>
        </el-dialog>

        <!-- 操作区 -->
        <div class="toolbar mb-2">
            <el-button @click="onAddTag">添加标签</el-button>
            <el-button @click="onExport">导出数据</el-button>
        </div>

        <!-- 用户表格 -->
        <el-table :data="tableData" border stripe style="width: 100%" @selection-change="onSelectionChange">
            <el-table-column type="selection" width="50" />
            <el-table-column prop="UserId" label="ID编号" min-width="80" />
            <el-table-column prop="UserName" label="用户账号" min-width="120" />
            <el-table-column prop="MembershipLevel" label="会员等级" min-width="120" />
            <el-table-column prop="IsEnabled" label="用户状态" min-width="100">
                <template #default="scope">
                    <el-tag v-if="scope.row.IsEnabled" type="success" effect="plain">● 正常</el-tag>
                    <el-tag v-else type="danger" effect="plain">● 禁用</el-tag>
                </template>
            </el-table-column>
            <el-table-column prop="OrderLogs" label="订单记录" min-width="100">
                <template #default="scope">
                    <el-link type="primary">{{ scope.row.OrderLogs }}</el-link>
                </template>
            </el-table-column>
            <el-table-column prop="ConsumptionAmount" label="消费金额" min-width="120">
                <template #default="scope">
                    ￥{{ scope.row.ConsumptionAmount.toFixed(2) }}
                </template>
            </el-table-column>
            <el-table-column prop="AvailablePoints" label="可用积分" min-width="120" />
            <el-table-column label="操作" min-width="240">
                <template #default="scope">
                    <el-button type="primary" plain @click="onShowDetail(scope.row)">详情</el-button>
                    <el-button type="primary" plain @click="onEdit(scope.row)">编辑</el-button>
                    <el-button type="danger" plain @click="onDelete(scope.row)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>

        <!-- 分页 -->
        <CustomPagination class="mt-2" :currentPage="pageIndex" :pageSize="pageSize" :totalCount="pageInfo.totalCount"
            :totalPage="pageInfo.totalPage" @size-change="onPageSizeChange" @current-change="onCurrentPageChange" />

        <!-- 编辑弹窗 -->
        <el-dialog v-model="editDialog.visible" title="修改资料" width="500px">
            <el-form :model="userFormData" label-width="90px" :rules="editRules" ref="editFormRef">
                <el-form-item label="用户账号:" prop="UserName" required>
                    <el-input v-model="userFormData.UserName" disabled />
                </el-form-item>
                <el-form-item label="手机号:" prop="Phone" required>
                    <el-input v-model="userFormData.Phone" />
                </el-form-item>
                <el-form-item label="会员等级:" prop="MembershipLevel" required>
                    <el-radio-group v-model="userFormData.MembershipLevel">
                        <el-radio-button label="普通会员" />
                        <el-radio-button label="黄金会员" />
                        <el-radio-button label="白金会员" />
                        <el-radio-button label="钻石会员" />
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="性别:" prop="Gender" required>
                    <el-radio-group v-model="userFormData.Gender">
                        <el-radio-button label="男" />
                        <el-radio-button label="女" />
                        <el-radio-button label="保密" />
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="生日:" prop="Birthday">
                    <el-date-picker v-model="userFormData.Birthday" type="date" placeholder="选择日期" style="width: 100%"
                        format="YYYY-MM-DD" value-format="YYYY-MM-DD" />
                </el-form-item>
                <el-form-item label="所在城市:" prop="City" required>
                    <el-select v-model="userFormData.City" placeholder="选择城市" style="width: 100%">
                        <el-option v-for="city in cityOptions" :key="city" :label="city" :value="city" />
                    </el-select>
                </el-form-item>
                <el-form-item label="职业:" prop="Occupation" required>
                    <el-input v-model="userFormData.Occupation" />
                </el-form-item>
                <el-form-item label="个性签名:" prop="PersonalSignature">
                    <el-input v-model="userFormData.PersonalSignature" />
                </el-form-item>
            </el-form>
            <template #footer>
                <el-button @click="editDialog.visible = false">取消</el-button>
                <el-button type="primary" @click="onEditSave">保存</el-button>
            </template>
        </el-dialog>

        <!-- 详情弹窗 -->
        <el-dialog v-model="detailDialog.visible" title="用户详情" width="500px">
            <el-descriptions :column="1" border>
                <el-descriptions-item label="用户账号">{{ detailDialog.data.UserName }}</el-descriptions-item>
                <el-descriptions-item label="手机号">{{ detailDialog.data.Phone }}</el-descriptions-item>
                <el-descriptions-item label="会员等级">{{ detailDialog.data.MembershipLevel }}</el-descriptions-item>
                <el-descriptions-item label="性别">{{ detailDialog.data.Gender || '保密' }}</el-descriptions-item>
                <el-descriptions-item label="生日">
                    {{ formatBirthday(detailDialog.data.Birthday) }}
                </el-descriptions-item>
                <el-descriptions-item label="所在城市">{{ detailDialog.data.City || '未设置' }}</el-descriptions-item>
                <el-descriptions-item label="职业">{{ detailDialog.data.Occupation || '未设置' }}</el-descriptions-item>
                <el-descriptions-item label="个性签名">{{ detailDialog.data.PersonalSignature || '未设置'
                    }}</el-descriptions-item>
                <el-descriptions-item label="用户状态">
                    <el-tag v-if="detailDialog.data.IsEnabled" type="success" effect="plain">● 正常</el-tag>
                    <el-tag v-else type="danger" effect="plain">● 禁用</el-tag>
                </el-descriptions-item>
                <el-descriptions-item label="订单记录">{{ detailDialog.data.OrderLogs }}</el-descriptions-item>
                <el-descriptions-item label="消费金额">￥{{ detailDialog.data.ConsumptionAmount?.toFixed(2)
                    }}</el-descriptions-item>
                <el-descriptions-item label="可用积分">{{ detailDialog.data.AvailablePoints }}</el-descriptions-item>
            </el-descriptions>
            <template #footer>
                <el-button @click="detailDialog.visible = false">关闭</el-button>
            </template>
        </el-dialog>
    </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { getUserList, type UserListParams, type UserItem, deleteUser, type UserListData, updateUser, exportUser } from '@/api/user'
import { ElMessage, ElMessageBox } from 'element-plus'
import CustomPagination from '@/components/CustomPagination.vue'

// 明确定义用户更新参数类型
interface UpdateUserParams {
    UserId: number;
    UserName: string;
    Phone: string;
    MembershipLevel: string;
    Gender: string;
    Birthday: string; // 使用string类型
    City: string;
    Occupation: string;
    PersonalSignature: string;
    IsEnabled: boolean;
}

// 查询参数，和后端DTO一致
const query = reactive<UserListParams>({
    UserId: undefined, // 用户ID
    UserName: '', // 用户名
    Phone: '', // 手机号
    MembershipLevel: '', // 会员等级
    UserTags: '', // 用户标签
    RegistrationChannel: '', // 注册渠道
    IsEnabled: undefined, // 用户状态，使用undefined而不是null
    RegisterTimeStart: '', // 注册起始时间
    RegisterTimeEnd: '', // 注册结束时间
    ConsumptionAmountMin: undefined, // 消费金额最小值
    ConsumptionAmountMax: undefined // 消费金额最大值
})
const pageIndex = ref<number>(1)
const pageSize = ref<number>(10)

// 注册时间区间
const registerTime = ref([]);
// 消费金额区间（字符串，格式如"100-200"）
const amountRange = ref('')
// 账号状态复选框
const statusNormal = ref(false)
const statusDisabled = ref(false)
// 高级筛选弹窗显示控制
const showAdvanced = ref(false)

// 高级筛选：注册时间区间 ref
const advancedRegisterTime = ref([]);

// 新增：消费金额范围选项
const consumptionAmountOptions = [
    { label: '全部金额', value: '' },
    { label: '100元以下', value: '0-100' },
    { label: '100-500元', value: '100-500' },
    { label: '500-1000元', value: '500-1000' },
    { label: '1000-5000元', value: '1000-5000' },
    { label: '5000元以上', value: '5000-Infinity' }
];

// 高级筛选表单
const advanced = reactive({
    UserName: '',
    MembershipLevel: '',
    UserTags: '',
    RegistrationChannel: '',
    consumptionAmountRange: '', // 新增：消费金额范围的选中值
    IsEnabled: false as boolean // 改为具体的boolean值，不使用null
})

// 用户表格数据
const tableData = ref<UserItem[]>([])
// 总条数和总页数
const pageInfo = reactive({
    totalCount: 0, // 总条数
    totalPage: 0   // 总页数
})
// 多选选中的用户
const selected = ref<UserItem[]>([])

// 编辑弹窗数据
const editDialog = reactive({
    visible: false,
    originalRow: null as (UserItem & Record<string, any>) | null, // 保存原始行数据，用于比较哪些字段被修改
    form: {
        UserId: '', UserName: '', Phone: '', MembershipLevel: '', Gender: '', Birthday: '', City: '', Occupation: '', PersonalSignature: ''
    }
})

// 单独的表单对象，用于存储和验证所有字段
const userFormData = reactive<UpdateUserParams>({
    UserId: 0,
    UserName: '',
    Phone: '',
    MembershipLevel: '',
    Gender: '',
    Birthday: '', // 使用空字符串替代null
    City: '',
    Occupation: '',
    PersonalSignature: '',
    IsEnabled: true
});

// 详情弹窗数据
const detailDialog = reactive<{ visible: boolean, data: Partial<UserItem> & Record<string, any> }>({
    visible: false,
    data: {}
})
// 编辑表单ref
const editFormRef = ref()
// 编辑表单校验规则
const editRules = {
    UserName: [{ required: true, message: '请输入用户账号', trigger: 'blur' }],
    Phone: [{ required: true, message: '请输入手机号', trigger: 'blur' }],
    MembershipLevel: [{ required: true, message: '请选择会员等级', trigger: 'change' }],
    Gender: [{ required: true, message: '请选择性别', trigger: 'change' }],
    City: [{ required: true, message: '请选择城市', trigger: 'change' }],
    Occupation: [{ required: true, message: '请输入职业', trigger: 'blur' }]
}

// 热门城市选项
const cityOptions = [
    '北京', '上海', '广州', '深圳', '杭州', '南京', '成都', '重庆', '西安', '苏州', '武汉', '天津', '青岛', '厦门', '郑州'
]

// 获取用户列表数据
const fetchData = async () => {
    try {
        // 处理注册时间区间
        if (registerTime.value && registerTime.value.length === 2) {
            query.RegisterTimeStart = registerTime.value[0]
            query.RegisterTimeEnd = registerTime.value[1]
        } else {
            query.RegisterTimeStart = ''
            query.RegisterTimeEnd = ''
        }
        // 处理消费金额区间
        if (amountRange.value) {
            const [min, max] = amountRange.value.split('-').map(s => s.trim())
            query.ConsumptionAmountMin = min ? Number(min) : undefined
            query.ConsumptionAmountMax = max ? Number(max) : undefined
        } else {
            query.ConsumptionAmountMin = undefined
            query.ConsumptionAmountMax = undefined
        }
        // 处理账号状态
        if (statusNormal.value && !statusDisabled.value) query.IsEnabled = true
        else if (!statusNormal.value && statusDisabled.value) query.IsEnabled = false
        else query.IsEnabled = null

        // 保证分页参数为 number
        if (typeof pageIndex.value !== 'number' || isNaN(pageIndex.value)) pageIndex.value = 1
        if (typeof pageSize.value !== 'number' || isNaN(pageSize.value)) pageSize.value = 10
        // 合并分页参数
        const params: UserListParams = {
            ...query,
            pageIndex: pageIndex.value,
            pageSize: pageSize.value
        }

        // 请求用户列表，使用 as any 解决类型问题
        const response = await getUserList(params) as any;

        // 检查响应状态
        if (!response || !response.IsSuc || (response.Code !== 200 && response.Code !== 0)) {
            ElMessage.error(response?.Msg || '获取用户列表失败');
            tableData.value = []
            pageInfo.totalCount = 0
            pageInfo.totalPage = 0
            return;
        }

        // 获取数据
        const res = response.Data as UserListData;

        // 使用返回的数据
        tableData.value = res.Data || []
        pageInfo.totalCount = res.TotalCount || 0
        pageInfo.totalPage = res.TotalPage || 0
    } catch (error: any) {
        console.error('获取用户列表失败:', error)
        // 显示错误信息
        ElMessage.error(error.message || '获取用户列表失败')
        // 清空表格数据
        tableData.value = []
        pageInfo.totalCount = 0
        pageInfo.totalPage = 0
    }
}

// 查询按钮
const onSearch = () => {
    pageIndex.value = 1
    fetchData()
}
// 重置按钮
const onReset = () => {
    query.UserId = undefined
    query.UserName = ''
    query.Phone = ''
    query.MembershipLevel = ''
    query.UserTags = ''
    query.RegistrationChannel = ''
    registerTime.value = []
    amountRange.value = ''
    statusNormal.value = false
    statusDisabled.value = false
    pageIndex.value = 1
    pageSize.value = 10 // Ensure pageSize is also reset
    fetchData()
}

// Page size change handler for CustomPagination
const onPageSizeChange = (newSize: number) => {
    pageSize.value = newSize
    pageIndex.value = 1 // Reset to first page when page size changes
    fetchData()
}

// Current page change handler for CustomPagination
const onCurrentPageChange = (newPage: number) => {
    pageIndex.value = newPage
    fetchData()
}

// 多选变化
const onSelectionChange = (rows: UserItem[]) => {
    selected.value = rows
}

// 添加标签按钮点击事件 (示例)
const onAddTag = () => {
    ElMessage.info('点击了添加标签按钮（功能待实现）');
}

// 重置高级筛选表单的方法
const resetAdvancedForm = () => {
    advanced.UserName = '';
    advanced.MembershipLevel = '';
    advanced.UserTags = '';
    advanced.RegistrationChannel = '';
    advancedRegisterTime.value = [];
    advanced.consumptionAmountRange = ''; // 重置消费金额范围
    advanced.IsEnabled = false;
};

// 高级筛选弹窗确定
const onAdvancedConfirm = () => {
    // 用户账号/ID/手机号 (合并到 UserName 进行查询)
    if (advanced.UserName) query.UserName = advanced.UserName;
    else query.UserName = '';

    // 会员等级
    if (advanced.MembershipLevel) query.MembershipLevel = advanced.MembershipLevel;
    else query.MembershipLevel = '';

    // 用户标签
    if (advanced.UserTags) query.UserTags = advanced.UserTags;
    else query.UserTags = '';

    // 注册渠道
    if (advanced.RegistrationChannel) query.RegistrationChannel = advanced.RegistrationChannel;
    else query.RegistrationChannel = '';

    // 处理高级筛选的注册时间区间
    if (advancedRegisterTime.value && advancedRegisterTime.value.length === 2) {
        // 日期已经是字符串格式，直接使用
        query.RegisterTimeStart = advancedRegisterTime.value[0];
        query.RegisterTimeEnd = advancedRegisterTime.value[1];
    } else {
        query.RegisterTimeStart = '';
        query.RegisterTimeEnd = '';
    }

    // 处理消费金额范围
    query.ConsumptionAmountMin = undefined;
    query.ConsumptionAmountMax = undefined;
    if (advanced.consumptionAmountRange) {
        const [minStr, maxStr] = advanced.consumptionAmountRange.split('-');
        if (minStr && minStr !== 'undefined' && minStr !== 'null') {
            query.ConsumptionAmountMin = Number(minStr);
        }
        if (maxStr && maxStr !== 'Infinity' && maxStr !== 'undefined' && maxStr !== 'null') {
            query.ConsumptionAmountMax = Number(maxStr);
        } else if (maxStr === 'Infinity') {
            query.ConsumptionAmountMax = undefined; // Infinity 表示无上限
        }
    }

    // 账号状态
    query.IsEnabled = advanced.IsEnabled; // null, true, false

    showAdvanced.value = false;
    fetchData();
}
// 编辑弹窗打开，反填数据
const onEdit = (row: UserItem & Record<string, any>) => {
    // 保存原始行数据
    editDialog.originalRow = { ...row };

    // 直接填充到单独的表单对象
    userFormData.UserId = row.UserId ? Number(row.UserId) : 0;
    userFormData.UserName = row.UserName || '';
    userFormData.Phone = row.Phone || '';
    userFormData.MembershipLevel = row.MembershipLevel || '';

    console.log('原始行数据:', row);
    console.log('性别字段值:', row.Gender, '类型:', typeof row.Gender);

    // 特别处理性别字段，根据后端返回值进行匹配
    const gender = row.Gender || '';
    if (!gender) {
        // 如果为空，默认为保密
        userFormData.Gender = '保密';
    } else if (gender === '男' || gender === 'male') {
        userFormData.Gender = '男';
    } else if (gender === '女' || gender === 'female') {
        userFormData.Gender = '女';
    } else {
        // 其他情况默认为"保密"
        userFormData.Gender = '保密';
    }

    console.log('处理后的性别值:', userFormData.Gender);

    // 处理生日，确保是正确的日期格式或空字符串
    if (row.Birthday) {
        try {
            // 尝试解析日期并格式化为YYYY-MM-DD格式
            const date = new Date(row.Birthday);
            if (!isNaN(date.getTime())) {
                const year = date.getFullYear();
                const month = (date.getMonth() + 1).toString().padStart(2, '0');
                const day = date.getDate().toString().padStart(2, '0');
                userFormData.Birthday = `${year}-${month}-${day}`;
                console.log('格式化后的生日:', userFormData.Birthday);
            } else {
                userFormData.Birthday = '';
                console.log('无效的生日日期');
            }
        } catch (e) {
            console.error('日期格式化错误:', e);
            userFormData.Birthday = '';
        }
    } else {
        userFormData.Birthday = '';
    }

    userFormData.City = row.City || '';
    userFormData.Occupation = row.Occupation || '';
    userFormData.PersonalSignature = row.PersonalSignature || '';
    userFormData.IsEnabled = row.IsEnabled !== undefined ? row.IsEnabled : true;

    // 打开编辑弹窗
    editDialog.visible = true;

    // 强制下一个渲染周期更新表单值，解决反填问题
    setTimeout(() => {
        editFormRef.value && editFormRef.value.clearValidate();
    }, 0);
}

// 编辑弹窗保存
const onEditSave = async () => {
    if (!editFormRef.value || !editDialog.originalRow) return;

    editFormRef.value.validate(async (valid: boolean) => {
        if (!valid) {
            ElMessage.warning('请填写所有必填字段');
            return;
        }

        try {
            // 调用更新接口之前，准备提交的数据
            const updateParams: UpdateUserParams = {
                UserId: userFormData.UserId,
                UserName: userFormData.UserName,
                Phone: userFormData.Phone,
                MembershipLevel: userFormData.MembershipLevel,
                Gender: userFormData.Gender,
                Birthday: userFormData.Birthday || '', // 确保始终有值
                City: userFormData.City,
                Occupation: userFormData.Occupation,
                PersonalSignature: userFormData.PersonalSignature,
                IsEnabled: userFormData.IsEnabled
            };

            // 特殊处理生日字段
            if (userFormData.Birthday) {
                // 如果已经是YYYY-MM-DD格式，就直接使用
                updateParams.Birthday = userFormData.Birthday;
            } else {
                updateParams.Birthday = '';
            }

            console.log('即将提交的表单数据:', updateParams);

            // 调用更新接口
            const response = await updateUser(updateParams) as any;

            // 检查响应状态
            if (!response || !response.IsSuc || (response.Code !== 200 && response.Code !== 0)) {
                ElMessage.error(response?.Msg || '保存用户资料失败');
                return;
            }

            // 显示成功消息
            ElMessage.success('保存用户资料成功');

            // 关闭弹窗
            editDialog.visible = false;

            // 刷新用户列表
            fetchData();
        } catch (error: any) {
            console.error('保存用户资料失败:', error);
            // 显示错误信息
            ElMessage.error(error.message || '保存用户资料失败，请检查网络连接');
        }
    })
}
// 详情弹窗打开
const onShowDetail = (row: UserItem & Record<string, any>) => {
    // 处理数据，避免undefined值
    const processedData = { ...row };

    console.log('详情查看 - 原始性别值:', processedData.Gender);

    // 确保性别字段正确显示
    const gender = processedData.Gender || '';
    if (!gender) {
        processedData.Gender = '保密';
    } else if (gender === '男' || gender === 'male') {
        processedData.Gender = '男';
    } else if (gender === '女' || gender === 'female') {
        processedData.Gender = '女';
    } else {
        processedData.Gender = '保密';
    }

    console.log('详情查看 - 处理后性别值:', processedData.Gender);

    // 更新详情弹窗数据
    detailDialog.data = processedData;
    detailDialog.visible = true;
}
// 删除用户
const onDelete = async (row: UserItem & Record<string, any>) => {
    try {
        await ElMessageBox.confirm(
            `确定要删除用户 " ${row.UserName} " 吗？此操作不可恢复。`,
            '删除确认',
            {
                confirmButtonText: '确定删除',
                cancelButtonText: '取消',
                type: 'warning',
            }
        );

        // 调用删除接口，使用 as any 解决类型问题
        const response = await deleteUser({ UserId: row.UserId }) as any;

        // 检查响应状态
        if (!response || !response.IsSuc || (response.Code !== 200 && response.Code !== 0)) {
            ElMessage.error(response?.Msg || '删除用户失败');
            return;
        }

        // 显示成功消息
        ElMessage.success(`用户 " ${row.UserName} " 删除成功`);

        // 重新加载列表
        fetchData();

    } catch (error: any) {
        // 如果用户点击了"取消"，ElMessageBox.confirm 会 reject 一个 error，通常是字符串 'cancel'
        if (error !== 'cancel') {
            console.error('删除用户失败:', error);
            // 显示错误消息
            ElMessage.error(error.message || '删除用户失败');
        }
    }
}

// 格式化生日显示
const formatBirthday = (birthday: string | null | undefined): string => {
    if (!birthday) return '未设置';
    try {
        const date = new Date(birthday);
        if (isNaN(date.getTime())) return '未设置';

        // 格式化为YYYY-MM-DD形式
        const year = date.getFullYear();
        const month = (date.getMonth() + 1).toString().padStart(2, '0');
        const day = date.getDate().toString().padStart(2, '0');

        return `${year}-${month}-${day}`;
    } catch (e) {
        console.error('日期格式化错误:', e);
        return '未设置';
    }
}
//导出用户信息
const onExport = async () => {
    try {
        const response = await exportUser();

        // 创建Blob对象
        const blob = new Blob([response.data], {
            type: response.headers['content-type']
        });

        // 从响应头中获取文件名，如果没有则使用默认名称
        let filename = 'users_export.xlsx';
        const contentDisposition = response.headers['content-disposition'];
        if (contentDisposition) {
            const filenameMatch = contentDisposition.match(/filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/);
            if (filenameMatch && filenameMatch[1]) {
                filename = filenameMatch[1].replace(/['"]/g, '');
            }
        }

        // 创建下载链接并模拟点击
        const downloadLink = document.createElement('a');
        downloadLink.href = URL.createObjectURL(blob);
        downloadLink.download = filename;
        document.body.appendChild(downloadLink);
        downloadLink.click();

        // 清理
        document.body.removeChild(downloadLink);
        URL.revokeObjectURL(downloadLink.href);

        ElMessage.success('导出成功');
    } catch (error) {
        console.error('导出失败:', error);
        ElMessage.error('导出失败，请稍后重试');
    }
}

// 页面加载时获取数据
onMounted(fetchData)

</script>

<style scoped>
.user-manage {
    background: #fff;
    border-radius: 8px;
    padding: 12px;
    min-height: 600px;
    box-shadow: 0 2px 8px 0 rgba(0, 0, 0, 0.03);
    width: 100%;
}

.page-title {
    font-size: 20px;
    font-weight: bold;
    margin-bottom: 12px;
}

.query-form {
    margin-bottom: 10px;
}

.toolbar {
    margin-bottom: 10px;
}

.mt-2 {
    margin-top: 10px;
}

.mb-2 {
    margin-bottom: 10px;
}

:deep(.dialog-right) {
    position: fixed !important;
    right: 0;
    top: 0;
    margin: 0;
    width: 800px;
    height: 100vh;
    display: flex;
    align-items: stretch;
    z-index: 3000;
}

:deep(.dialog-right .el-dialog) {
    margin: 0 !important;
    height: 100vh;
    border-radius: 0;
    box-shadow: -2px 0 8px 0 rgba(0, 0, 0, 0.08);
    display: flex;
    flex-direction: column;
}

/* 新增：高级筛选弹窗头部样式 */
:deep(.dialog-right .el-dialog__header) {
    padding-bottom: 15px;
    margin-right: 0;
    /* 覆盖element plus可能存在的margin */
    border-bottom: 1px solid #eee;
    font-size: 18px;
    /* 适当增大标题字号 */
    font-weight: bold;
    /* 加粗标题 */
}

/* 调整标题文本的内边距，确保和关闭按钮对齐美观 */
:deep(.dialog-right .el-dialog__title) {
    padding-left: 10px;
}

/* 新增：为弹窗脚部添加上边框，增强分隔感 */
:deep(.dialog-right .el-dialog__footer) {
    border-top: 1px solid #eee;
    padding: 10px 20px;
    /* 统一一下脚部内边距 */
    text-align: right;
    /* 确保按钮在脚部右对齐 */
}

/* 如果之前有对 .dialog-footer 的内联样式，可以考虑统一到这里 */
.dialog-footer .el-button:first-child {
    margin-right: 10px;
    /* 给取消按钮和确定按钮之间加一点间距 */
}

/* 美化高级筛选弹窗内部样式 */
:deep(.dialog-right .el-dialog__body) {
    padding: 25px 30px;
    /* 调整弹窗内容区的内边距 */
}

:deep(.dialog-right .el-form .el-form-item) {
    margin-bottom: 22px;
    /* 统一表单项的下边距，增加呼吸感 */
}

/* 清除栅格布局下 el-form-item 默认的一些宽度影响，确保能撑满 el-col */
:deep(.dialog-right .el-form .el-row .el-form-item) {
    width: 100%;
}

:deep(.dialog-right .el-form .el-input),
:deep(.dialog-right .el-form .el-date-editor.el-input),
:deep(.dialog-right .el-form .el-select) {
    /* max-width: 320px; 注释掉之前的最大宽度，因为现在由 el-col 控制 */
    width: 100%;
    /* 在最大宽度内，宽度为100%以适应容器 */
}
</style>